<?php
// app/Controller/UsersController.php

class PropiedadesController extends AppController {

	public $dbName 		= 'dbinmo';
	public $dbUserName 	= 'root';
	public $dbUserPass 	= '';

	public $helpers = array('Js' => array('Jquery'));
	public $scaffold = 'admin';

	public function cropear ($original, $width_final, $height_final, $final){
		$imgInfo = getimagesize ($original);
		$width = $imgInfo[0];
		$height = $imgInfo[1];
		$display_crop = imagecreatetruecolor($width_final, $height_final);
		if ($imgInfo['mime']=='image/jpeg')
				$source = imagecreatefromjpeg($original);
		if    ($imgInfo['mime']=='image/png')
				$source = imagecreatefrompng($original);
		if    ($imgInfo['mime']=='image/gif')
				$source = imagecreatefromgif($original);

		if (($width/$height) > ($width_final / $height_final) )           
			{ 
				$rel = ($height_final/$height);
				$ancho_relativo=($width_final/$rel);
				$ancho_quitar=$width-$ancho_relativo;
				$ancho_quitar=$ancho_quitar/2;
				imagecopyresampled($display_crop, $source, 0, 0, $ancho_quitar, 0, $width_final,$height_final, $ancho_relativo, $height);
				switch ($imgInfo['mime'])
					{
						case 'image/jpeg':
							{imagejpeg($display_crop, $final); echo ('es jpg'); }
						case 'image/png':
							imagepng($display_crop, $final);
						case 'image/gif':
							imagegif($display_crop, $final);
					}
			}
		else   
			{   
				$rel = ($width_final/$width);
				$alto_relativo=($height_final/$rel);
				$alto_quitar=$height-$alto_relativo;
				$alto_quitar=$alto_quitar/2;
				imagecopyresampled($display_crop, $source, 0, 0, 0, $alto_quitar, $width_final,$height_final, $width, $alto_relativo);
				switch ($imgInfo['mime'])
					{
						case 'image/jpeg':
							imagejpeg($display_crop, $final);
						case 'image/png':
							imagepng($display_crop, $final);
						case 'image/gif':
							imagegif($display_crop, $final);
					}
			}   
	}	

	public function beforeFilter() {
		parent::beforeFilter();
		
	}

    public function index() {
		
		$db = NewADOConnection('mysql');
		$db->Connect('localhost', $this->dbUserName, $this->dbUserPass, $this->dbName);
		$db->execute("SET NAMES utf8");
		
		$this->set('title_for_layout', 'Listado de Propiedades');
		$this->set('listTitle', 'Listado de Propiedad');
		
	
		
		$url 				= $_SERVER['REQUEST_URI'];
		$filtros 			= new Filtros_propiedades($url,'$');
		
		$selected_filters 	= array();
		$filters 			= array();
		$_GET['pag']		= $filtros->page;
		
		$results 			= $filtros->get_results();

		foreach($filtros->filters_list as $filtro){
			if ($filtro['selected']){
				$selected_filters[$filtro['field_denomination']] = $filtro;
			}
			else{
				if (count($results) > 1){
					$filters[] = $filtro;
				}
			}
		}
		
		
		$filters_data = array(
			'selected_filters' => $selected_filters,
			'filter_type'		=> 'LINKS_FILTERS',
			'product_name' 		=> array(
				'single' 		=> 'propiedad',
				'multiple' 		=> 'propiedades'
			),
			'base_url' 			=> $filtros->base_url,
			'description_url'	=> $filtros->description_url,
			'currency'  		=> '$',
			'filters' 			=> $filters
		);
		
        $this->set('filters_data', $filters_data);
        $this->set('propiedades', $results);		
        $this->set('urlOrdenador', $filtros->url . '/pag/' . $filtros->page);

		$db = NewADOConnection('mysql');
		$db->Connect('localhost', $filtros->dbUserName, $filtros->dbUserPass, $filtros->dbName);
		// Pasar a UTF-8
        $db->execute("SET NAMES utf8");

		
		$url_orden = "";
		if($filtros->order_by != ""){
			$url_orden = '/order/' . $filtros->order_by;
		}
		
		
		
		$paginador = new PaginadorHelper($db, $this);
		$paginador->urlPaginador		= $filtros->url;
		$paginador->url_orden			= $url_orden;
		$paginador->friendly_urls 		= false;
		$paginador->smarty_array 		= 'propiedades';
		$paginador->nombre_unidades 	= 'propiedades';
		$paginador->total_por_pagina 	= 7;
		$paginador->MostrarArray( $results );
		$this->set('url', $filtros->url_den);
		$this->set('pais', $filtros->filtros_obligatorios['pais']);
		$this->set('order', $filtros->order_by);
			
    }

    public function view($id = null) {
	
		$root_path 		= $_SERVER['DOCUMENT_ROOT'];
		$gallery_files  = $this->get_dir_images('galeria',$id);
		
		
		
		
        $this->set('title_for_layout', 'Propiedad');
		$this->Propiedad->id = $id;
		$this->set('prop', $this->Propiedad->read());
		$this->set('gallery_files', $gallery_files);
	
		
		
    }

    public function add() {
        
		$this->set('title_for_layout', 'Agregar Propiedad');
		$this->set('listTitle', 'Agregar Propiedad');
		
		
		if ($this->request->is('post')) {
            if ($this->Propiedad->save($this->request->data)) {
                $this->Session->setFlash(__('Se ha creado la Propiedad'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('La propiedad no pudo cargarse. Por favor intente nuevamente.'));
            }
        }
    }

    public function edit($id = null) {
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
            }
        } else {
            $this->request->data = $this->User->read(null, $id);
            unset($this->request->data['User']['password']);
        }
    }

    public function admin_delete($id = null) {
        if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        $this->Propiedad->id = $id;
        if (!$this->Propiedad->exists()) {
            throw new NotFoundException(__('Invalid propiedad'));
        }
        if ($this->Propiedad->delete()) {
			$this->delete_images($id);
            $this->Session->setFlash(__('Propiedad deleted'));
            $this->redirect(array('action' => 'index'));
        }
		
        $this->Session->setFlash(__('Propiedad was not deleted'));
        $this->redirect(array('action' => 'index'));
    }
	public function admin_index(){
		$this->layout='back_end';
		$this->set('title_for_layout', 'Listado de Propiedades');
		$this->set('listTitle', 'Listado de propiedades');  
		$this->Propiedad->recursive = 0;		
		$this->set('propiedades', $this->paginate());		
		//$this->set('propiedades', $this->Propiedad->find('all'));
    }	

	public function admin_add() {
		
		$db = NewADOConnection('mysql');
		$db->Connect('localhost', $this->dbUserName, $this->dbUserPass, $this->dbName);
		$db->execute("SET NAMES utf8");
	
	
		$this->set('title_for_layout', 'Agregar Propiedad');
		$this->set('listTitle', 'Agregar Propiedad'); 
		$this->layout='back_end';

		$zona = $this->Propiedad->Zona->find('list', array(
			'fields' => array('Zona.descripcion'),
			'recursive' => 0
		));
		$tipo = $this->Propiedad->Tipo_inmueble->find('list', array(
			'fields' => array('Tipo_inmueble.descripcion'),
			'recursive' => 0
		));
		$region = $this->Propiedad->Zona->Region->find('list', array(
			'fields' => array('Region.descripcion'),
			'recursive' => 0
		));		
		$pais = $this->Propiedad->Zona->Region->Pais->find('list', array(
			'fields' => array('Pais.descripcion'),
			'recursive' => 0
		));
		
		$query_destacadas = 'SELECT COUNT( id ) AS total
								FROM propiedades
								WHERE destacada != "0000-00-00 00:00:00"';
								
		$cantidad_destacadas = (int)$db->getOne($query_destacadas);
		
		$this->set('zona_id',$zona);		
		$this->set('tipo_id',$tipo);		
		$this->set('region_id',$region);
		$this->set('pais_id',$pais);
		$this->set('cantidad_destacadas',$cantidad_destacadas);
	
		if ($this->request->is('post')) {
			//$this->request->data['Propiedad']['user_id'] = $this->Auth->user('id'); //Added this line
            if ($this->Propiedad->save($this->request->data)) {
                $this->Session->setFlash('Se ha guardado la Propiedad.','default',Utils::messageType('ok'));
				$id = $this->Propiedad->getInsertId();
				$root_path = $_SERVER['DOCUMENT_ROOT'];
				if (!empty($_FILES['imagenes_0']['name'])){
					foreach($_FILES as $key => $current_image){
						$name_exploded 		= explode('_',$key);
						$position 			= $name_exploded[1];
						$temp_file_path 	= $current_image['tmp_name'];
						$new_file_name  	= 'prop_' . $id . '_' . $position . '.jpg';
						$new_file_path		= $root_path . '/app/webroot/upload/prop_images/originales/' . $new_file_name;
						$new_gall_file_path	= $root_path . '/app/webroot/upload/prop_images/galeria/' . $new_file_name;
						$new_list_file_path	= $root_path . '/app/webroot/upload/prop_images/list/prop_' . $id . '.jpg';
						$new_dest_file_path	= $root_path . '/app/webroot/upload/prop_images/dest/prop_' . $id . '.jpg';
						copy($temp_file_path,$new_file_path);
						$this->cropear($new_file_path,300,177,$new_gall_file_path);
						if ($position == 0){
							$this->cropear($new_file_path,190,112,$new_list_file_path);
							$this->cropear($new_file_path,156,92,$new_dest_file_path);
						}
					}
				}
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash('No se ha guardado la Propiedad.');
            }
        }
    }
	public function admin_edit($id = null) {
	
		$db = NewADOConnection('mysql');
		$db->Connect('localhost', $this->dbUserName, $this->dbUserPass, $this->dbName);
		$db->execute("SET NAMES utf8");
	
	
		$this->set('title_for_layout', 'Editar Cliente');
		$this->layout='back_end';
		

		$zona = $this->Propiedad->Zona->find('list', array(
			'fields' => array('Zona.descripcion'),
			'recursive' => 0
		));
		$tipo = $this->Propiedad->Tipo_inmueble->find('list', array(
			'fields' => array('Tipo_inmueble.descripcion'),
			'recursive' => 0
		));
		$region = $this->Propiedad->Zona->Region->find('list', array(
			'fields' => array('Region.descripcion'),
			'recursive' => 0
		));		
		$pais = $this->Propiedad->Zona->Region->Pais->find('list', array(
			'fields' => array('Pais.descripcion'),
			'recursive' => 0
		));
		
		$query_destacadas = 'SELECT COUNT( id ) AS total
								FROM propiedades
								WHERE destacada != "0000-00-00 00:00:00"';
								
		$cantidad_destacadas = (int)$db->getOne($query_destacadas);
		
		$images = $this->get_dir_images('galeria',$id);
		
		$counter = 1;
		$array_mayor = array();
		
		foreach($images as $image){
			$new_array[] = $image;
			if (($counter % 5 == 0) || $counter == count($images) ){
				$array_mayor[] 	= $new_array;
				$new_array		= array();
			}
			$counter++;
		}
		
		$this->set('zona_id',$zona);		
		$this->set('tipo_id',$tipo);		
		$this->set('region_id',$region);
		$this->set('pais_id',$pais);
		$this->set('cantidad_destacadas',$cantidad_destacadas);
		//echo '<pre>'; var_dump($images); echo '</pre>'; die();
		$this->set('images_array',$array_mayor);
		
		
		$this->Propiedad->id = $id;
		if ($this->request->is('get')) {
			$this->request->data = $this->Propiedad->read();
			$this->set('data',$this->request->data['Propiedad']);
		} else {
			$propiedad = $this->Propiedad->read();
			$propiedad = $propiedad['Propiedad'];
			
			
			if (isset($this->request->data['Propiedad']['destacada'])){
				if ($propiedad['destacada'] == '0000-00-00 00:00:00'){
					$this->request->data['Propiedad']['destacada'] = date('Y-m-d h:i:s');
					if ($cantidad_destacadas >= 6){
						$desmarcar_query = 'UPDATE propiedades SET destacada = "0000-00-00 00:00:00" 
											WHERE destacada != "0000-00-00 00:00:00"
											ORDER BY destacada 
											LIMIT 1';
						$db->Execute($desmarcar_query);
					}
				}
			}
			
			if ($this->Propiedad->save($this->request->data)) {
				$this->Session->setFlash('El Cliente '. $id . ' ha sido actualizado.', 'default', Utils::messageType('ok'));
				$root_path 		= $_SERVER['DOCUMENT_ROOT'];
				$dir_images 	= $this->get_dir_images('originales',$id);
				
				$images_qty		= count($dir_images);
				
				$position 		= 0;
				if ($images_qty > 0){
					$position 		= (int)$dir_images[$images_qty-1] + 1;
				}
				
				if (!empty($_FILES['imagenes_0']['name'])){
					foreach($_FILES as $key => $current_image){
					
						
					
						$name_exploded 		= explode('_',$key);
						$temp_file_path 	= $current_image['tmp_name'];
						$new_file_name  	= 'prop_' . $id . '_' . $position . '.jpg';
						$new_file_path		= $root_path . '/app/webroot/upload/prop_images/originales/' . $new_file_name;
						$new_gall_file_path	= $root_path . '/app/webroot/upload/prop_images/galeria/' . $new_file_name;
						$new_list_file_path	= $root_path . '/app/webroot/upload/prop_images/list/prop_' . $id . '.jpg';
						$new_dest_file_path	= $root_path . '/app/webroot/upload/prop_images/dest/prop_' . $id . '.jpg';
						copy($temp_file_path,$new_file_path);
						$this->cropear($new_file_path,300,177,$new_gall_file_path);
						if ($position == 0){
							$this->cropear($new_file_path,190,112,$new_list_file_path);
							$this->cropear($new_file_path,156,92,$new_dest_file_path);
						}
						$position++;
					}
				}
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash('No se pudo actualizar el cliente.');
			}
			
			
		}
	}	
	public function admin_view($id = null) {
		$this->layout='back_end';
		$this->set('title_for_layout', 'Vista de Propiedad');
		$this->set('listTitle', 'Vista de Propiedad'); 
		$this->Propiedad->id = $id;
        $this->set('propiedad', $this->Propiedad->read());
    }		
	public function get_dir_images($dir,$id){
		$path 			= $_SERVER['DOCUMENT_ROOT'] . '/app/webroot/upload/prop_images/' . $dir; 
		$files_list 	= scandir($path);
		$return_array	= array();
		for($i=0;$i<count($files_list);$i++){
			$exploded = explode('.',$files_list[$i]);
			$name	  = $exploded[0];
			$exploded = explode('_',$name);
			
			if( isset($exploded[0]) && $exploded[0] == 'prop'){
				if( isset($exploded[1]) && $exploded[1] == $id){
					if (isset($exploded[2])){
						$return_array[] = $exploded[2];
					}
				}
			}
		}
		return $return_array; 
	}
	public function delete_images($id_prop=null){
		$path 		= $_SERVER['DOCUMENT_ROOT'] . '/app/webroot/upload/prop_images/';
		
		$gallery_images_ids 	= $this->get_dir_images('galeria',$id_prop);
		$original_images_ids 	= $this->get_dir_images('originales',$id_prop);
		
		unlink( $path . 'dest/prop_' . $id_prop . '.jpg');
		unlink( $path . 'list/prop_' . $id_prop . '.jpg');
		foreach($original_images_ids as $image_id){
			unlink( $path . 'originales/prop_' . $id_prop . '_' . $image_id . '.jpg');
		}
		foreach($gallery_images_ids as $image_id){
			unlink( $path . 'galeria/prop_' . $id_prop . '_' . $image_id . '.jpg');
		}
	}
}